<script>
import {doDelete, doDownload, doGet, doPost, doPut} from "../../http/httpRequest.js";
import {PAGE_SIZE} from "../../contants/constants.js";
import {msgConfirm, msgTip} from "../../util/util.js";

export default {
  name: "DictView",
  inject:['reload'],
  data() {
    return {
      // 查询数据字典
      queryDict: {},
      dictTypeList:[],
      dataList:[],
      pageSize: PAGE_SIZE,
      total: 0,
      selectedRows: [],
      dialogTitle: "",
      addDictTypeDialogVisible: false,
      dictType: {}, // 新增,编辑数据字典
      originalDictType: {}, // 编辑时，保存原始数据
      dictTypeRules: {
        type: [
          { required: true, message: "请输入数据字典类型", trigger: "blur" },
          { validator: this.validateDictTypeType, trigger: "blur" }
        ],
        desc: [
          { required: true, message: "请输入数据字典描述", trigger: "blur" }
        ]
      }
    }
  },
  methods: {
    // 获取字典类型列表
    getDictTypeList() {
      doGet("system/dict/all").then(resp => {
        if (resp.data.code === 200) {
          this.dictTypeList = resp.data.data;
        }
      })
    },
    search() {
      this.getData(1);
    },
    reset() {
      this.queryDict = {};
      this.getData(1);
    },
    getData(current) {
      doGet("/system/dict/list", {
        pageNum: current,
        type: this.queryDict.type,
        desc: this.queryDict.desc
      }).then(resp => {
        if (resp.data.code === 200) {
          this.dataList = resp.data.data.list;
          this.pageSize = resp.data.data.pageSize;
          this.total = resp.data.data.total;
        }
      });
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection.map(item => item.id);
    },
    handleCurrentChange(current) {
      this.getData(current);
    },
    /* 新增 */
    addDictType() {
      this.dialogTitle = "新增数据字典";
      this.addDictTypeDialogVisible = true;
      this.dictType = {};
    },
    /* 批量删除 */
    batchDelDictType() {
      // 如果未选择任何行则提示
      if(this.selectedRows.length === 0) {
        msgTip("请选择要删除的数据字典","warning");
        return;
      }

      msgConfirm("确定要删除吗？").then(()=>{
        const ids = this.selectedRows.join(",");
        doDelete("/system/dict/batchDelete",{ ids : ids }).then(resp => {
          if(resp.data.code === 200) {
            msgTip("删除成功","success");
            this.reload();
          }
        })
      }).catch(() => {
        msgTip("取消了删除", 'warning');
      })
    },
    /* 编辑 */
    edit(id) {
      this.dialogTitle = "编辑数据字典";
      // 根据id获取数据字典
      doGet("/system/dict/" + encodeURI(id) ).then(resp => {
        if(resp.data.code === 200) {
          this.dictType = resp.data.data;
          this.originalDictType = {...resp.data.data};
          this.addDictTypeDialogVisible = true;
        } else {
          msgTip("获取数据字典失败","error");
        }
      });
    },
    /* 删除 */
    del(id) {
      msgConfirm("确定要删除吗？").then(()=>{
        doDelete("/system/dict/delete/" + encodeURI(id)).then(resp => {
          if(resp.data.code === 200) {
            msgTip("删除成功","success");
            this.reload();
          } else {
            msgTip("删除失败","error");
          }
        })
      }).catch(() => {
        msgTip("取消了删除", 'warning');
      })
    },
    /* 进入详情 */
    values(id) {
      // 路由跳转到详情页面
      this.$router.push({
        name: "DictDetailView",
        params: {
          id: id
        }
      });

    },

    addDictTypeSubmit(){
      this.$refs.dictTypeRefForm.validate(valid => {
        if(valid) {
          if(this.dictType.id > 0) {
            console.log("编辑")
            // 编辑操作
            doPut("/system/dict/update", this.dictType).then(resp => {
              if(resp.data.code === 200) {
                // 编辑成功
                msgTip("编辑数据字典成功","success");
                this.reload();
              } else {
                msgTip("编辑数据字典失败","error");
              }
            });
          } else {
            // 新增操作
            doPost("/system/dict/add", this.dictType).then(resp => {
              if(resp.data.code === 200) {
                // 新增成功
                msgTip("新增数据字典成功","success");
                this.reload();
              } else {
                msgTip("新增数据字典失败","error");
              }
            });
          }
        }
      })
    },

    /* 导出Excel */
    exportDictExcel() {
      doDownload("/system/dict/export", {
        type: this.queryDict.type,
        desc: this.queryDict.desc}).then(resp => {
          const url = window.URL.createObjectURL(new Blob([resp.data]));
          const link = document.createElement("a");
          link.href = url;
          const contentDisposition = resp.headers['content-disposition'];
          let filename = 'Dict.xlsx';
          if (contentDisposition) {
            let filenameMatch = contentDisposition.match(/filename=(.+);?/);
            if(filenameMatch && filenameMatch[1]) {
              let fn = filenameMatch[1].trim();
              // 如果前后有多余的"则去掉这个字符
              if(fn.startsWith('"') && fn.endsWith('"')) {
                fn = fn.slice(1,-1);
              }
              filename = decodeURIComponent(fn);
            }
          }
          link.setAttribute("download", filename);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
      }).catch(error => {
        msgTip("导出失败","error");
      })
    },

    /****************  新增数据字典的校验  ******************/
    validateDictTypeType(rule,value,callback) {
      // 判断vlaue中是否包含字符/
      if (value.indexOf("/") !== -1) {
        callback(new Error("字典类型不能包含/"));
      }
      if (!this.dictType.id || (this.dictType.id && this.originalDictType.type !== value)) {
        doGet("/system/dict/hasType", {
          type: value
        }).then(resp => {
          if (resp.data.code === 200) {
            if (resp.data.data) {
              callback(new Error("字典类型已存在！"))
            } else {
              callback();
            }
          }
        }).catch(() => {
          callback(new Error("数据校验失败，请稍后再试"));
        });
      } else {

        callback();
      }
    }
  },
  mounted() {
    this.getDictTypeList();
    this.getData(1);
  }
}
</script>

<template>
  <!-- 查询区域 -->
  <el-form :inline="true" :model="queryDict" class="query-form">
    <el-form-item label="字典类型">
      <!-- 添加下拉选项 -->
      <el-select v-model="queryDict.type" clearable placeholder="请选择" filterable>
        <el-option
            v-for="item in dictTypeList"
            :key="item.type"
            :label="item.desc"
            :value="item.type">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="字典描述">
      <el-input v-model="queryDict.desc" placeholder="请输入字典名称" clearable></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </el-form-item>
  </el-form>

  <el-divider/>

  <div class="op-btn">
    <el-button type="primary" class="btn" @click="addDictType">新增字典</el-button>
    <el-button type="danger" class="btn" @click="batchDelDictType">批量删除</el-button>
    <el-button type="info" class="btn" @click="exportDictExcel">导出Excel</el-button>
  </div>

  <el-table
    :data="dataList"
    style="width:100%"
    @selection-change="handleSelectionChange"
    class="custom-table"
    border
    stripe>
    <el-table-column type="selection" width="50" />
    <el-table-column type="index" label="序号" width="80" />
    <el-table-column prop="type" label="字典类型" />
    <el-table-column prop="desc" label="字典描述" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" @click="edit(scope.row.id)" size="small">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.id)" size="small">删除</el-button>
        <el-button type="warning" @click="values(scope.row.id)" size="small">详情</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination background
                 layout="prev, pager, next, jumper, total"
                 :page-size="pageSize"
                 :total="total"
                 @current-change="handleCurrentChange"
                 class="pagination" />

  <!-- 新增数据字典 -->
  <el-dialog :title="dialogTitle" v-model="addDictTypeDialogVisible" width="35%" :close-on-click-modal="false">
    <el-form ref="dictTypeRefForm" :model="dictType" label-width="110px" :rules="dictTypeRules">
      <el-form-item label="数据字典类型" prop="type">
        <el-input v-model="dictType.type" placeholder="请输入数据字典类型" clearable></el-input>
      </el-form-item>
      <el-form-item label="数据字典描述" prop="desc">
        <el-input v-model="dictType.desc" placeholder="请输入数据字典描述" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDictTypeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addDictTypeSubmit">提交</el-button>
      </span>
    </template>
  </el-dialog>

</template>

<style scoped>
.query-form {
  .el-input {
    width: 220px;
  }
  .el-select {
    width: 220px;
  }
}

.op-btn {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start;
}

.custom-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}
.custom-table ::v-deep th {
  background-color: rgb(190, 190, 190) ; /* 背景色 */
  color: #303133;
  font-weight: bold; /* 加粗字体 */
}

.custom-table ::v-deep th,
.custom-table ::v-deep td {
  padding: 10px;
  text-align: left;
}


.custom-table ::v-deep tr:nth-child(even) {
  background-color: #f9f9f9;
}

.custom-table ::v-deep tr:hover {
  background-color: #f1f1f1;
}


.pagination {
  margin-top: 20px;
}

.button-column {
  display: flex;
  flex-direction: column;
  gap: 5px; /* 设置按钮之间的间距 */
  .el-button {
    width: 80px;
    margin-left: 0 !important;
  }
}

</style>